package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {

    @DubboReference
    RecommendUserService recommendUserService;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    VisitorService visitorService;

    @DubboReference
    UserLocationService userLocationService;

    @DubboReference
    QuestionService questionService;

    //今日佳人
    public ResponseEntity findTodayBest() {
        //1.获取当前登陆者id
        //2.远程调用service查询推荐用户
        RecommendUser recommendUser = recommendUserService.findTodayBest(UserHolder.get().getId());

        //3.假如这个推荐用户存在的话,拿到用户id查询userInfo
        if (recommendUser == null) {
            //注意:该登陆用户有可能是首次登陆,大数据系统还没有给当前登陆者推荐用户,推荐用户就为空
            recommendUser = new RecommendUser();
            recommendUser.setScore(99D);
            recommendUser.setUserId(1L);
        }

        UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());

        //4.封装RecommendUserVo对象,设置userInfo和缘分值
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());

        //5.将vo对象返回
        return ResponseEntity.ok(vo);
    }

    //推荐用户分页查询
    public ResponseEntity findRecommendUserByPage(Integer pageNum, Integer pageSize) {
        //1.获取登陆者id
        //2.远程调用service查询分页列表
        PageBeanVo pageBeanVo = recommendUserService.findByPage(UserHolder.get().getId(), pageNum, pageSize);

        //3.获取pageBeanVo中集合,遍历集合,获取每个推荐用户的id,然后获取userInfo,封装RecommendUserVo对象,将vo对象放入一个voList.
        //3.0 创建voList
        List<RecommendUserVo> voList = new ArrayList<>();

        //3.1 获取pageBeanVo中集合
        List<RecommendUser> items = (List<RecommendUser>) pageBeanVo.getItems();

        //3.2 遍历集合,获取每个推荐用户的id
        if (CollUtil.isNotEmpty(items)) {
            items.forEach(e->{
                //3.3 获取userInfo
                UserInfo userInfo = userInfoService.findByUserId(e.getUserId());

                //3.4 封装RecommendUserVo对象
                RecommendUserVo vo = new RecommendUserVo();
                vo.setUserInfo(userInfo);
                vo.setFateValue(e.getScore().longValue());

                //3.5 将vo对象放入voList中
                voList.add(vo);
            });
        }

        //4.给pageBeanVo设置voList,且返回
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    //最近访客
    public ResponseEntity findVisitorsTop5() {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.去redis中获取最后访问时间
        String time = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);

        //3.远程调用service获取最近访客list
        //注意:新用户还没有最后访问时间

        //新建voList
        ArrayList<VisitorVo> voList = new ArrayList<>();

        if (StrUtil.isNotBlank(time)) {
            List<Visitor> visitors = visitorService.findVisitorsTop5(userId, Long.parseLong(time));

            //4.遍历list,获取每个访客的userInfo,将userInfo封装成visitorVo,将每个vo放入voList中
            //4.1 遍历list
            if (CollUtil.isNotEmpty(visitors)) {
                visitors.forEach(e->{
                    //4.2 获取每个访客的userInfo
                    UserInfo userInfo = userInfoService.findByUserId(e.getVisitorUserId());

                    //4.3 将userInfo封装成visitorVo
                    VisitorVo vo = new VisitorVo();
                    vo.setUserInfo(userInfo);
                    vo.setFateValue(e.getScore().longValue());

                    //4.4 将每个vo放入voList中
                    voList.add(vo);
                });
            }


        }
        //5.将当前时间设置为最后访问时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME+userId,System.currentTimeMillis()+"");

        //6.将voList返回
        return ResponseEntity.ok(voList);
    }



    //查询推荐用户详情
    public ResponseEntity findPersonalInfo(Long recommendUserId) {
        //1.调用userInfoService查询userInfo
        UserInfo userInfo = userInfoService.findByUserId(recommendUserId);

        //2.远程调用service查询指定的推荐用户
        RecommendUser recommendUser = recommendUserService.findPersonalInfo(UserHolder.get().getId(), recommendUserId);

        //注意:推荐用户有可能不存在
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setScore(RandomUtil.randomDouble(70,100));
        }

        //3.获取缘分值
        //4.封装recommendUserVo且返回
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());

        return ResponseEntity.ok(vo);
    }

    //上报地址位置
    public void saveUserLocation(Double longitude, Double latitude, String addrStr) {
        userLocationService.save(longitude,latitude,addrStr,UserHolder.get().getId());
    }

    //搜附近
    public ResponseEntity searchNear(String gender, Long distance) {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.调用service获取附近人的id集合
        List<Long> ids = userLocationService.searchNear(userId, distance);

        //3.遍历id集合,获取每个userInfo,将userInfo封装NearUserVo对象,将vo对象返回voList
        //3.1 创建voList
        List<NearUserVo> voList = new ArrayList<>();

        //3.2 遍历id集合,
        if (CollUtil.isNotEmpty(ids)) {
            for (Long id : ids) {
                //判断:排除自己 因为是包装类,所以使用equals进行比较
                if (userId.equals(id)) {
                    continue;
                }

                //3.3 获取每个userInfo
                UserInfo userInfo = userInfoService.findByUserId(id);

                //判断:性别
                if (!userInfo.getGender().equals(gender)) {
                    continue;
                }

                //3.4 将userInfo封装NearUserVo对象,
                NearUserVo vo = new NearUserVo();
                vo.setUserId(id);
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                //3.5 将vo对象放入voList
                voList.add(vo);
            }
        }

        //4.返回voList
        return ResponseEntity.ok(voList);
    }

    public ResponseEntity findStrangerQuestion(Long userId) {
        //1.根据id查询用户的问题对象
        Question question = questionService.findByUserId(userId);

        //2.判断问题对象是否为空,若为空需要设置默认问题
        if (question == null) {
            question = new Question();
        }

        //3.返回问题
        return ResponseEntity.ok(question.getStrangerQuestion());
    }
}
